package com.zzy.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zzy.product.entity.AttrAttrgroupRelationEntity;
import com.zzy.product.entity.AttrEntity;
import com.zzy.product.entity.AttrGroupEntity;
import com.zzy.product.entity.CategoryEntity;
import com.zzy.product.mapper.AttrAttrgroupRelationMapper;
import com.zzy.product.mapper.AttrGroupMapper;
import com.zzy.product.mapper.AttrMapper;
import com.zzy.product.mapper.CategoryMapper;
import com.zzy.product.service.AttrService;
import com.zzy.product.service.CategoryService;
import com.zzy.product.vo.AttrGroupRelationVo;
import com.zzy.product.vo.AttrRespVo;
import com.zzy.product.vo.AttrVo;
import com.zzy.utils.constant.ProductConstant;
import com.zzy.utils.utils.PageUtils;
import com.zzy.utils.utils.Query;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import javax.management.QueryEval;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrMapper, AttrEntity> implements AttrService {

	@Autowired
	private AttrAttrgroupRelationMapper relationMapper;
	
	@Autowired
	private AttrGroupMapper attrGroupMapper;
	
	@Autowired
	private CategoryMapper categoryMapper;
	
	@Autowired
	private CategoryService categoryService;
	
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }
	
	@Transactional
	@Override
	public void saveAttr(AttrVo attr) {
		AttrEntity attrEntity = new AttrEntity();
		BeanUtils.copyProperties(attr, attrEntity);
		/*1、保存基本数据*/
		this.save(attrEntity);
		/*2、保存关联关系*/
		if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
			AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
			relationEntity.setAttrGroupId(attr.getAttrGroupId());
			relationEntity.setAttrId(attrEntity.getAttrId());
			relationMapper.insert(relationEntity);
		}
	}
	
	@Override
	public PageUtils queryBaseAttrPage(Map<String, Object> params, Long catelogId, String attrType) {
		QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
				.eq("attr_type", "base".equalsIgnoreCase(attrType)?
						ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode():
						ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
		if (catelogId != 0) {
			queryWrapper.eq("catelog_id", catelogId);
		}
		String key = (String) params.get("key");
		if (!StringUtils.isEmpty(key)) {
			// attr_id attr_name
			queryWrapper.and((wrapper) -> {
				wrapper.eq("attr_id", key).or().like("attr_name", key);
			});
		}
		IPage<AttrEntity> page = this.page(
				new Query<AttrEntity>().getPage(params),
				queryWrapper
		);
		PageUtils pageUtils = new PageUtils(page);
		List<AttrEntity> records = page.getRecords();
		List<AttrRespVo> respVos = records.stream().map((attrEntity) -> {
			AttrRespVo attrRespVo = new AttrRespVo();
			BeanUtils.copyProperties(attrEntity, attrRespVo);
			/*设置分类和分组名字*/
			if ("base".equalsIgnoreCase(attrType)) {
				AttrAttrgroupRelationEntity attrId = relationMapper.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().
						eq("attr_id", attrEntity.getAttrId()));
				if (attrId != null) {
					AttrGroupEntity attrGroupEntity = attrGroupMapper.selectById(attrId.getAttrGroupId());
					if (attrGroupEntity != null) {
						attrRespVo.setGroupName(attrGroupEntity.getAttrGroupName());
					}
				}
			}
			CategoryEntity categoryEntity = categoryMapper.selectById(attrEntity.getCatelogId());
			if (categoryEntity != null) {
				attrRespVo.setCatelogName(categoryEntity.getName());
			}
			return attrRespVo;
		}).collect(Collectors.toList());
		pageUtils.setList(respVos);
		return pageUtils;
	}
	
	@Override
	public AttrRespVo getAttrInfo(Long attrId) {
		AttrRespVo respVo = new AttrRespVo();
		AttrEntity attrEntity = this.getById(attrId);
		BeanUtils.copyProperties(attrEntity, respVo);
		/*设置分组信息*/
		if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
			AttrAttrgroupRelationEntity attrgroupRelation = relationMapper.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>()
					.eq("attr_id", attrId));
			if (attrgroupRelation != null) {
				respVo.setAttrGroupId(attrgroupRelation.getAttrGroupId());
				AttrGroupEntity attrGroupEntity = attrGroupMapper.selectById(attrgroupRelation.getAttrGroupId());
				if (attrGroupEntity != null) {
					respVo.setAttrName(attrGroupEntity.getAttrGroupName());
				}
			}
		}
		
		/*设置分类信息*/
		Long catelogId = attrEntity.getCatelogId();
		Long[] catelogPath = categoryService.findCatelogPath(catelogId);
		respVo.setCatelogPath(catelogPath);
		CategoryEntity categoryEntity = categoryMapper.selectById(catelogId);
		if (categoryEntity != null) {
			respVo.setAttrName(categoryEntity.getName());
		}
		return respVo;
	}
	
	@Transactional
	@Override
	public void updateAttr(AttrVo attr) {
		AttrEntity attrEntity = new AttrEntity();
		BeanUtils.copyProperties(attr, attrEntity);
		this.updateById(attrEntity);
		
		if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
			AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
			relationEntity.setAttrGroupId(attr.getAttrGroupId());
			relationEntity.setAttrId(attr.getAttrId());
			Long count = relationMapper.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
			if (count > 0) {
				/*修改分组关联*/
				relationMapper.update(relationEntity,
						new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
			} else {
				relationMapper.insert(relationEntity);
			}
		}
	}
	
	/**
	 * 根据分组id查找关联的所有属性
	 * @param attrgroupId 分组id
	 * @return
	 */
	@Override
	public List<AttrEntity> getRelationInfo(Long attrgroupId) {
		List<AttrAttrgroupRelationEntity> entities = relationMapper.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
				.eq("attr_group_id", attrgroupId));
		List<Long> attrIds = entities.stream().map((attr) -> {
			return attr.getAttrId();
		}).collect(Collectors.toList());
		if (attrIds == null || attrIds.size() == 0) {
			return null;
		}
		List<AttrEntity> attrEntities = this.listByIds(attrIds);
		return attrEntities;
		
	}
	
	@Override
	public void deleteRelation(AttrGroupRelationVo[] vos) {
		List<AttrAttrgroupRelationEntity> entities = Arrays.asList(vos).stream().map((item) -> {
			AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
			BeanUtils.copyProperties(item, relationEntity);
			return relationEntity;
		}).collect(Collectors.toList());
		relationMapper.deleteBatchRelation(entities);
	}
	
	/**
	 * 获取属性分组没有关联的其他属性
	 * /product/attrgroup/{attrgroupId}/noattr/relation
	 * @return
	 */
	@Override
	public PageUtils getNoAttrRelation(Long attrgroupId, Map<String, Object> params) {
		/*1、当前分组只能关联自己所属的分类里面的所有属性*/
		AttrGroupEntity attrGroupEntity = attrGroupMapper.selectById(attrgroupId);
		Long catelogId = attrGroupEntity.getCatelogId();
		/*2、当前分组只能关联别的分组没有引用的属性*/
		/*2.1、当前分类下的其他分组*/
		List<AttrGroupEntity> groups = attrGroupMapper.selectList(new QueryWrapper<AttrGroupEntity>()
				.eq("catelog_id", catelogId));
		List<Long> groupIds = groups.stream().map((item) -> {
			return item.getAttrGroupId();
		}).collect(Collectors.toList());
		/*2.2、这些分组关联的属性*/
		List<AttrAttrgroupRelationEntity> groupId = relationMapper.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
				.in("attr_group_id", groupIds));
		List<Long> attrIds = groupId.stream().map((item) -> {
			return item.getAttrId();
		}).collect(Collectors.toList());
		/*2.3、当前分类的所有属性中移除这些属性*/
		QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>()
				.eq("catelog_id", catelogId)
				.eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
		if (attrIds != null && attrIds.size() > 0) {
			wrapper.notIn("attr_id", attrIds);
		}
		String key = (String) params.get("key");
		if (!StringUtils.isEmpty(key)) {
			wrapper.and((w) -> {
				w.eq("attr_id", key).or().like("attr_name", key);
			});
		}
		IPage<AttrEntity> entityIPage = this.page(new Query<AttrEntity>().getPage(params), wrapper);
		return new PageUtils(entityIPage);
	}
	
}

















